package com.zzx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzx.common.exception.ServiceException;
import com.zzx.entity.TGx;
import com.zzx.mapper.TGxMapper;
import com.zzx.service.TGxService;
import com.zzx.utils.EntityUtils;
import com.zzx.utils.PageUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author zzx
 * @description 针对表【t_gx(工序表)】的数据库操作Service实现
 * @createDate 2025-06-14
 */
@Service
public class TGxServiceImpl extends ServiceImpl<TGxMapper, TGx>
        implements TGxService {


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(TGx param) {
        LambdaQueryWrapper<TGx> wrapper = new LambdaQueryWrapper<>(TGx.class);
        // 多租户拦截器会自动添加 company_id 条件
        wrapper.eq(TGx::getGxName, param.getGxName());

        if (ObjectUtils.isEmpty(param.getGxId())) {
            param.setGxId(IdUtil.getSnowflakeNextId());
        } else {
            wrapper.ne(TGx::getGxId, param.getGxId());
            TGx dbEntity = this.getBaseMapper().selectById(param.getGxId());
            if (dbEntity != null) {
                EntityUtils.mergeNonNullProperties(dbEntity, param);
            }
        }

        List<TGx> existList = this.getBaseMapper().selectList(wrapper);
        if (!existList.isEmpty()) {
            throw new ServiceException("工序名称已存在");
        }

        this.saveOrUpdate(param);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteById(TGx param) {
        this.removeById(param.getGxId());
    }

    @Override
    public IPage<TGx> selectBy(TGx param) {
        LambdaQueryWrapper<TGx> wrapper = new LambdaQueryWrapper<>(TGx.class);

        if (!ObjectUtils.isEmpty(param.getGxName())) {
            wrapper.like(TGx::getGxName, param.getGxName());
        }
        if (!ObjectUtils.isEmpty(param.getGxCode())) {
            wrapper.like(TGx::getGxCode, param.getGxCode());
        }
        if (!ObjectUtils.isEmpty(param.getGxId())) {
            wrapper.eq(TGx::getGxId, param.getGxId());
        }

        // 多租户拦截器会自动添加 company_id 条件
        wrapper.orderByDesc(TGx::getCreateTime);

        return this.getBaseMapper().selectPage(
                PageUtils.createPage(param.getPageNum(), param.getPageSize()),
                wrapper
        );
    }

    @Override
    public TGx findById(String id) {
        return this.getBaseMapper().selectById(id);
    }
}
